package krow.dev.addetector;

import java.util.List;

import krow.dev.addetector.control.Module;
import krow.dev.addetector.control.ModuleSacnner;
import krow.dev.addetector.model.ApplicationItem;
import krow.dev.addetector.util.DisplayUtil;
import krow.dev.addetector.util.SystemBarTintManager;
import krow.dev.addetector.view.FloatingButton;
import krow.dev.addetector.view.LinkableTextView;
import krow.dev.addetector.view.adapter.ApplicationListAdapter;
import krow.dev.addetector.view.dialog.ModuleInfoDialog;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

public class MainActivity extends ActionBarActivity {

	private ApplicationListAdapter mApplicationListAdapter;
	private ListView mApplicationListView;
	private View mHeaderView;
	private View mFooterview;
	private FloatingButton mRefreshButton;
	
	private ModuleSacnner mModuleScanner;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		setupActionbar();
		initializeView();
	}

	private void setupActionbar(){
		getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME);
		getSupportActionBar().setTitle(R.string.app_name);
	}
	
	@SuppressLint("InflateParams")
	private void initializeView(){
		int headerHeight = DisplayUtil.getStatusBarHeight(getApplicationContext()) + DisplayUtil.getActionBarHeight(getApplicationContext());
		int footerHeight = DisplayUtil.getNavigationBarHeight(getApplicationContext());
		
		boolean isOverlay = false;
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
			isOverlay = true;
			int dummyViewWidth = LayoutParams.MATCH_PARENT; 
			
			mHeaderView = new View(getApplicationContext());
			mHeaderView.setLayoutParams(new ListView.LayoutParams(dummyViewWidth, headerHeight));
			mFooterview = new View(getApplicationContext());
			mFooterview.setLayoutParams(new ListView.LayoutParams(dummyViewWidth, footerHeight));
			
			SystemBarTintManager systemBarTintManager = new SystemBarTintManager(this);
			systemBarTintManager.setStatusBarTintEnabled(true);
			systemBarTintManager.setNavigationBarTintEnabled(true);
			systemBarTintManager.setTintColor(getResources().getColor(R.color.teal700));
		}
		bindRefreshButton(isOverlay ? 0 : headerHeight);
		
		mApplicationListAdapter = new ApplicationListAdapter(getApplicationContext());
		mApplicationListAdapter.setOnLinkClickListener(mLinkClickListener);
		mApplicationListView = (ListView) findViewById(R.id.list_package);
		mApplicationListView.setOnItemClickListener(mApplicationItemClickListener);
		mApplicationListView.addFooterView(getLayoutInflater().inflate(R.layout.footer_dummy, null));
		if(mHeaderView != null){
			mApplicationListView.addHeaderView(mHeaderView);
		}
		if(mFooterview != null){
			mApplicationListView.addFooterView(mFooterview);
		}
		mApplicationListView.setAdapter(mApplicationListAdapter);
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		if(mApplicationListAdapter.getCount() <= 0){
			mRefreshButton.hide();
			scanModule();
		}
	}
	
	@Override
	protected void onStop() {
		stopScan();
		super.onStop();
	}
	
	private void bindRefreshButton(int headerSize){
		Log.e("test", "header size: " + headerSize);
		int size = DisplayUtil.getDimensionToPixel(getApplicationContext(), 72F);
		int margin = DisplayUtil.getDimensionToPixel(getApplicationContext(), 16F);
		
		int height = DisplayUtil.getDisplayHeight(getApplicationContext());
		
		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(size, size);
		layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
		layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		layoutParams.rightMargin = margin;
		layoutParams.bottomMargin = -size;
				
		Log.e("test", "height: " + height + " margin: " + margin + " size: " + size);
		
		mRefreshButton = new FloatingButton(getApplicationContext());
		mRefreshButton.setOnClickListener(mRefreshClickListener);
		mRefreshButton.setColor(getResources().getColor(R.color.teal));
		mRefreshButton.setDrawable(getResources().getDrawable(R.drawable.icon_refresh));
		mRefreshButton.setCurrentY(height - (margin + size + headerSize));
		mRefreshButton.setLayoutParams(layoutParams);
		ViewGroup rootView = (ViewGroup) findViewById(R.id.layout_frame);
		rootView.addView(mRefreshButton);
	}
	
	private void scanModule(){
		mModuleScanner = new ModuleSacnner(this);
		mModuleScanner.setOnCallbackListener(mModuleCallbackListener);
		mModuleScanner.execute();
	}
	
	private void stopScan(){
		if(mModuleScanner != null){
			mModuleScanner.stop();
			mModuleScanner = null;
		}
	}
	
	private void refresh(){
		if(mModuleScanner != null){
			mModuleScanner.stop();
			mModuleScanner = null;
		}
		mRefreshButton.hide();
		scanModule();
	}
	
	private ModuleSacnner.OnCallbackListener mModuleCallbackListener = new ModuleSacnner.OnCallbackListener() {
		
		@Override
		public void onStart() {
			
		}
		
		@Override
		public void onProgress(String name, int index, int size) {
			
		}
		
		@Override
		public void onCancel() {
			
			mRefreshButton.show();
		}
		
		@Override
		public void onCompletion(List<ApplicationItem> applicationItemList) {
			mApplicationListAdapter.setApplicationItemList(applicationItemList);
			mApplicationListAdapter.notifyDataSetChanged();
			
			mRefreshButton.show();
		}
	};
	
	private AdapterView.OnItemClickListener mApplicationItemClickListener = new AdapterView.OnItemClickListener() {
		
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			if (view.getTag() == null) {
				return;
			}
			ApplicationItem applicationItem = (ApplicationItem) view.getTag();
			PackageInfo packageInfo = applicationItem.getPackageInfo();
			
			
			try {
				Intent intent = new Intent();
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
					intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
					intent.setData(Uri.fromParts("package", packageInfo.packageName, null));
					startActivity(intent);
				} else {
					intent.setAction(Intent.ACTION_VIEW);
					intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
					intent.putExtra("pkg", packageInfo.packageName);
					intent.putExtra("com.android.settings.ApplicationPkgName", packageInfo.packageName);
					startActivity(intent);
				}
			} catch (Exception e) {

			}
		}
	};

	private LinkableTextView.OnLinkClickListener mLinkClickListener = new LinkableTextView.OnLinkClickListener() {
		
		@Override
		public void onTextLinkClick(View textView, Module module) {
			
			ModuleInfoDialog moduleInfoDialog = new ModuleInfoDialog(MainActivity.this);
			moduleInfoDialog.setTitle(module.toString());
			moduleInfoDialog.setContent(getString(module.getDescriptionId()));
			moduleInfoDialog.setCanceledOnTouchOutside(true);
			moduleInfoDialog.show();
		}
	};
	
	private View.OnClickListener mRefreshClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View view) {
			Log.e("test", "refresh click!!");
			refresh();
		}
	};
}
